Conditional (computer programming)
part 10/26 · 46.2 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
In Haskell 98, there is only an if expression, no if statement, and the else part is compulsory, as every expression must have some value.cite-ref-haskell98report-4-0[4] Logic that would be expressed with conditionals in other languages is usually expressed with pattern matching in recursive functions.
Because Haskell is lazy, it is possible to write control structures, such as if, as ordinary expressions; the lazy evaluation means that an if function can evaluate only the condition and proper branch (where a strict language would evaluate all three). It can be written like this:cite-ref-haskell-ifthenelse-proposal-5-0[5]
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
C-like languages
C and C-like languages have a special ternary operator (?:) for conditional expressions with a function that may be described by a template like this:
condition ? evaluated-when-true : evaluated-when-false
This means that it can be inlined into expressions, unlike if-statements, in C-like languages:
my_variable = x > 10 ? "foo" : "bar"; // In C-like languages
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────